using Acme.MeiTuan.SDK.Tools;
using WebApiClientCore;

namespace Acme.MeiTuan.SDK.Api;

public class MeiTuanGetSign : IApiParameter
{
    public string? app_id { get; set; }

    public string? app_secret { get; set; }
    
    public async Task OnRequestAsync(ApiParameterContext context)
    {
        var requestUri = context.HttpContext.RequestMessage.RequestUri;
        var keyValues = context.ParameterValue.ToDictionary();
        var nameValuePair = new List<KeyValuePair<string, string>>();

        foreach (var (key, value) in keyValues)
        {
            if (key.Equals(nameof(app_secret)) || value is null) continue;
            nameValuePair.Add(new KeyValuePair<string, string>(key, value?.ToString()));
        }
        
        var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
        
        nameValuePair.Add(new KeyValuePair<string, string>(nameof(timestamp), timestamp));

        var strDecode = requestUri + "?" + Sign.GetSingStr(nameValuePair) + app_secret;
        var sig = Sign.MD5Sign(strDecode);
        nameValuePair.Add(new KeyValuePair<string, string>(nameof(sig), sig));

        foreach (var (key, value) in nameValuePair)
            context.HttpContext.RequestMessage.AddUrlQuery(key, value);

        await Task.CompletedTask;
    }
}